package com.yqg.protection.utils;

/**
 * projectName:tt-inner
 * author:zxf
 * time:2024/9/12 11:08
 * description:
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class test {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = null;
        try {
            //创建服务端
            serverSocket = new ServerSocket(8000);
            //保持服务器端一直运行
            while (true){
                System.out.println("waiting for connect");
                //接受的客户端socket
                Socket socket = serverSocket.accept();
                //以字节输入流的方式将接受的socket内容读取
                InputStream inputStream = socket.getInputStream();
//                //创建接受字节流容器
//                byte[] bytes = new byte[1024];
//                //将socket中的字节流信息读取进准备好的字节容器
//                int readlen = inputStream.read(bytes);
                byte[] bytes = new byte[1024];
                int len;
                StringBuilder sb = new StringBuilder();
                //只有当客户端关闭它的输出流的时候，服务端才能取得结尾的-1
                while ((len = inputStream.read(bytes)) != -1) {
                    // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                    sb.append(new String(bytes, 0, len, "UTF-8"));
                }
                System.out.println("get message from client: " + sb);
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("客户端,我收到信息了".getBytes("UTF-8"));
                inputStream.close();
                outputStream.close();
                //将接受的字节流通过字符串的方式打印
                for (byte byte1:bytes) {
                    System.out.println(byte1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭服务端
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void bytes(byte[] bytes){
        byte aByte = bytes[1];

    }
}
